<script setup lang="ts">
import type { Props, Emits } from './utils/types'
import { ElMessage, ElLoading } from 'element-plus'
import { useAuth } from '@/stores/index'
import APIInformation from '@/api/information'

const dialogVisible = shallowRef(false)
const $props = defineProps<Props>()
const $emit = defineEmits<Emits>()
const { getInfo } = useAuth()

watch($props, (newValue) => {
    dialogVisible.value = newValue.modelValue
}, { immediate: true })

watch(dialogVisible, (newValue) => {
    $emit('update:modelValue', newValue)
})

const email = shallowRef<string>('')

function onBeforeClose() {
    email.value = ''
    dialogVisible.value = false
}


function submitChangeEmail() {
    const test = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
    if (!email.value) return ElMessage.error('请输入邮箱')
    if (!test.test(email.value)) return ElMessage.error('您的邮箱格式不正确')
    const loading = ElLoading.service({ lock: true })
    APIInformation.changePersonal({ email: email.value }).then(({ msg }) => {
        ElMessage.success(msg)
        getInfo()
        onBeforeClose()
    }).finally(() => {
        loading.close()
    })
}

</script>

<template>
    <el-dialog class="edit-username" v-model="dialogVisible" title="设置邮箱" width="800" destroy-on-close
        :before-close="onBeforeClose" :show-close="false">
        <template #header>
            <DialogClose title="设置邮箱" @close="onBeforeClose" />
        </template>
        <div class="con">
            <div class="con-item">
                <div class="label">邮箱：</div>
                <el-input class="value" type="text" v-model="email" size="large" placeholder="请输入邮箱" />
            </div>
            <button type="button" class="submit-btn" @click="submitChangeEmail">确认</button>
        </div>
    </el-dialog>
</template>

<style lang="scss" scoped>
.edit-username {
    .con {
        display: flex;
        flex-direction: column;
        padding-top: 20px;
        padding-bottom: 40px;

        .con-item {
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 20px 0;

            .value {
                width: 535px;
            }
        }

        .submit-btn {
            display: block;
            margin: 0 auto;
            margin-top: 42px;
            width: 231px;
            height: 40px;
            border-radius: 5px;
            background-color: rgba(15, 64, 245, 1);
            color: rgba(255, 255, 255, 1);
            font-size: 14px;
            border: none;
            cursor: pointer;
        }
    }
}
</style>
